<?php


/**
* 用户在登录或者登出多说评论框时为了通知当前使用多说的站点该用户已经登录或者登出，
* 当前站点可以设置登录和登出的回调地址，用户在完成多说的登录或登出后，
* 多说会回调当前站点设置的回调地址同时会带上code参数，
* 站点可以用code获取用户的access_token并通过access_token获取用户的信息。
* 通过这个功能可以实现登录多说的同时也登录当前使用多说的网站。
*/
function httpRequest($url, $method, $params){

    $userAgent = 'DuoshuoPhpSdk/0.3.0';
    $connecttimeout = 30;
    $timeout = 60;

    $args = array(
            'method' => $method,    //  GET/POST
            'timeout' => $timeout,  //  超时的秒数
            'redirection' => 5,     //  最大重定向次数
            'httpversion' => '1.0', //  1.0/1.1
            'user-agent' => $userAgent,
            //'blocking' => true,     //  是否阻塞
            'headers' 	=> array('Expect'=>''),   //  header信息
            'cookies' => array(),   //  关联数组形式的cookie信息
            //'compress' => false,    //  是否压缩
            //'decompress' => true,   //  是否自动解压缩结果
            'sslverify' => true,
            //'stream' => false,
            //'filename' => null      //  如果stream = true，则必须设定一个临时文件名
    );
    switch($method){
        case 'GET':
            $url .= '?' . http_build_query($params, null, '&');	// overwrite arg_separator.output
            break;
        case 'POST':
            $headers = array();
            $args['body'] =  http_build_query($params);
            break;
        default:
    }
    $http = new EasyHttp();
    $response = $http->request($url, $args);
    if (isset($response->errors)){
        if (isset($response->errors['http_request_failed'])){
            $message = $response->errors['http_request_failed'][0];
            if ($message == 'name lookup timed out')
                $message = 'DNS解析超时，请重试或检查你的主机的域名解析(DNS)设置。';
            elseif (stripos($message, 'Could not open handle for fopen') === 0)
                $message = '无法打开fopen句柄，请重试或联系多说管理员。http://dev.duoshuo.com/';
            elseif (stripos($message, 'Couldn\'t resolve host') === 0)
                $message = '无法解析duoshuo.com域名，请重试或检查你的主机的域名解析(DNS)设置。';
            elseif (stripos($message, 'Operation timed out after ') === 0)
                $message = '操作超时，请重试或联系多说管理员。http://dev.duoshuo.com/';
            throw new Duoshuo_Exception($message, Duoshuo_Exception::REQUEST_TIMED_OUT);
        }
        else
            throw new Duoshuo_Exception('连接服务器失败, 详细信息：' . json_encode($response->errors), Duoshuo_Exception::REQUEST_TIMED_OUT);
    }

    $json = json_decode($response['body'], true);
    return $json === null ? $response['body'] : $json;
}

/**
 * 
 * @param string $type
 * @param array $keys
 */
function getAccessToken( /* $type, $keys */ ) {
    include('EasyHttp.php');
    include('EasyHttp/Curl.php');
    include('EasyHttp/Cookie.php');
    include('EasyHttp/Encoding.php');
    include('EasyHttp/Fsockopen.php');
    include('EasyHttp/Proxy.php');
    include('EasyHttp/Streams.php');			 
    $end_point = 'http://api.duoshuo.com/';
    /**
     * 返回值格式
     * @ string
     */
     $format = 'json';

     $userAgent = 'DuoshuoPhpSdk/0.3.0';

     $connecttimeout = 30;
     $timeout = 60;

    //  引入常量定义文件
    include('global.php');

     $shortName = $DUOSHUO_SHORT_NAME; //"ibeginner";
     $secret = $DUOSHUO_SECRET; //"68ca027eb484ddbcbc457f23def09066";
     $accessToken;
     $http;
    
    $type = 'code';
    $codeStr = $_GET['code']; 
    $keys['code'] = $codeStr;
    $params = array(
        'client_id'	=>	$shortName,
        'client_secret' => $secret,
    );
    
    switch($type){
        case 'token':
            $params['grant_type'] = 'refresh_token';
            $params['refresh_token'] = $keys['refresh_token'];
            break;
        case 'code':
            $params['grant_type'] = 'authorization_code';
            $params['code'] = $keys['code'];
//			$params['redirect_uri'] = $keys['redirect_uri'];
            break;
        case 'password':
            $params['grant_type'] = 'password';
            $params['username'] = $keys['username'];
            $params['password'] = $keys['password'];
            break;
        default:
            throw new Duoshuo_Exception("wrong auth type");
    }

    $accessTokenUrl = 'http://api.duoshuo.com/oauth2/access_token';
    $response = httpRequest($accessTokenUrl, 'POST', $params);

    $token = $response;
    if ( is_array($token) && !isset($token['error']) ) {
        $access_token = $token['access_token'];
        if (isset($token['refresh_token'])) //	可能没有refresh_token
            $refresh_token = $token['refresh_token'];
    } else {
        throw new Duoshuo_Exception("get access token failed." . $token['error']);
    }

    //  获取登录用户的信息需要accesstoken和user_id
    //return $access_token;
    $user['user_key'] = $token['user_id'];
    $user['name'] = '';
    $params2 = array(
        'short_name'	=>	$shortName,
        'secret' => $secret,
        'access_token' => $access_token,
        'user' => $user
    );
    $getUserInfoUrl = 'http://api.duoshuo.com/sites/join.json';
    // array(2) { ["response"]=> array(8) { ["user_id"]=> string(8) "11910443" ["name"]=> string(15) "ubuntu鐨勭柉鐙�" ["url"]=> string(26) "http://weibo.com/ubuntuvim" ["avatar_url"]=> string(49) "http://tp3.sinaimg.cn/1816124554/50/40084473370/1" ["threads"]=> int(0) ["comments"]=> int(1) ["social_uid"]=> array(1) { ["weibo"]=> string(10) "1816124554" } ["email"]=> string(0) "" } ["code"]=> int(0) }
    $userInfo = httpRequest($getUserInfoUrl, 'POST', $params2);
    //var_dump($userInfo['response']);
//    $arr = $userInfo['response'];
    //echo $arr['name'];
    //  把登录成的用户信息设置到session中
    session_start();
    //  暂时不知道后面会使用到用户的那个信息，全部保存了
    $_SESSION['LOGINUSERINFO'] = $userInfo['response'];

    //  登录成功设置 cookie，直接使用 setcookie 一直无效！！不知道是不是 header 跳转的问题！
    //setcookie("user", "Alex Porter", time()+604800); // 指定cookie保存时间为一个星期：7*24*60*60
	$expire = gmdate('D, d-M-Y H:i:s \\G\\M\\T', time() + 604800);
    $domain = '; domain=' . $_SERVER['HTTP_HOST'];
    header('Set-Cookie: my_cookie_key='.$userInfo['response']['user_id'].'; expires=' . $expire . '; path=/' . $domain . '; HttpOnly', false);


    // 跳转回到登录时的页面
    //echo "from = ".$_GET['from'];
    $fromStr = "Location:".$_GET['from'];
    header($fromStr);
}


//  得到user_id accesstoken
getAccessToken();